package qa.tests;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.ArtifactUtils;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;

public class DependencyToClasspathHelper {

    public static void addPluginDependenciesToTestClasspath(MavenProject project, ArtifactFactory factory,
            List<Artifact> pluginArtifacts) throws MojoExecutionException {
        Map pluginArtifactMap = ArtifactUtils.artifactMapByVersionlessId(pluginArtifacts);
        Artifact assertCounter = (Artifact) pluginArtifactMap.get("qa.tests:assert-counter");
        if (assertCounter == null) {
            throw new MojoExecutionException("Couldn't find 'assert-counter' artifact in plugin dependencies");
        }

        assertCounter = artifactScopeToTest(factory, assertCounter);
        Set set = new LinkedHashSet();
        if (project.getDependencyArtifacts() != null) {
            set.addAll(project.getDependencyArtifacts());
        }
        set.add(assertCounter);
        project.setDependencyArtifacts(set);
    }

    private static Artifact artifactScopeToTest(ArtifactFactory factory, Artifact artifact) {
        return factory.createArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(),
                Artifact.SCOPE_TEST, artifact.getType());
    }

}
